package com.foo.CompressData;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.ejb.Stateless;


/**
 * Session Bean implementation class Archive
 */
@Stateless
public class Compress implements CompressRemote, CompressLocal {

	public int BUFFER = 2048;
    /**
     * Default constructor. 
     */
    public Compress() {
       
    }    

	@Override
	public String storeFile(String filePath, String archivePath) {
		String archiveFileName = null; 
		try
		{
			archiveFileName = getArchiveFileName(filePath);
			System.out.println("Archived File is: " + archiveFileName);
			if(archiveFileName == null || archiveFileName == "")
			{
				return archiveFileName;			
			}
			else
			{
				createArchiveFile(filePath, archiveFileName);
				deleteFile(filePath);
			}
			return archiveFileName;
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			return null;
		}
	}
	
	private boolean deleteFile(String fileName)
	{
		File f1 = new File(fileName);
		return f1.delete();
	}
	public String getArchiveFileName(String filePath)
	{
		String fileName = "";
		BufferedReader br = null;
		try
		{
			String fromDate = null,toDate = null;
			String strLine = null;
			
			if(new File(filePath).exists())
			{
				System.out.println("Path Exists!!!!");
				br = new BufferedReader(new FileReader(filePath));
				String s=null;
				
				int count = 0;
				while ((s = br.readLine()) != null && (s = s.trim()).length() > 0)
				{
					if(count == 0)
					{
						String content[] = s.split(",");
						if(content[0] != null)
						{
							try
							{
								Integer.parseInt(content[0]);
							}
							catch(NumberFormatException e)
							{
								System.out.println(e.getMessage());
							}
							fromDate = content[0];
							count ++;
						}
						else
						{
							return "";
						}
					}
					strLine = s;
				}
				String last = strLine;
				String content_last[] = last.split(",");
				if(content_last != null)
				{
					if(content_last[0] != null)
					{
						try
						{
							Integer.parseInt(content_last[0]);
						}
						catch(NumberFormatException e)
						{
							System.out.println(e.getMessage());
						}
						toDate = content_last[0];
					}
					else
					{
						return "";
					}	
				}				
			}
			fileName = fromDate + "-" + toDate +".zip";
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
		}
		finally
		{
			try 
			{
				br.close();
			} 
			catch (IOException e) {
				e.printStackTrace();
			}
		}
		return fileName;
	}
	
	public boolean createArchiveFile(String filePath,String archiveFileName)
	{
		BufferedInputStream origin = null;
		ZipOutputStream out = null;
		FileOutputStream dest = null;
		FileInputStream file = null;
		try
		{	
	        dest = new FileOutputStream(archiveFileName);
	        out = new ZipOutputStream(new BufferedOutputStream(dest));
	        byte data[] = new byte[BUFFER];
	        
	        file = new FileInputStream(filePath);
	        origin = new BufferedInputStream(file, BUFFER);
	        //String[] filename = filePath.split("\\\\");
	       
	        //ZipEntry entry = new ZipEntry(filename[filename.length -1]);
	        ZipEntry entry = new ZipEntry(filePath);
	        out.putNextEntry(entry);
	        int count;
	        while((count = origin.read(data, 0,BUFFER)) != -1) 
	        {
	           out.write(data, 0, count);
	        }
	        return true;
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			return false;
		}
		finally
		{
			try {
				origin.close();
				out.close();
				dest.close();
				file.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
	        
		}
	}

	@Override
	public String storeFile(String filePath) {
		/*File file = new File(filePath);
		int endIndex = filePath.lastIndexOf(file.separator);*/
		//String archivePath = filePath.substring(0,endIndex);
		return storeFile(filePath, filePath);
	}

	@Override
	public String storeFile(byte[] fileData,int startPos,int endPos) 
	{
		FileOutputStream fileOut;
		try
		{
			Date date = new Date() ; 
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss") ; 
			fileOut = new FileOutputStream(dateFormat.format(date) +".txt");                
			fileOut.write(fileData, startPos, (endPos - startPos));                
			fileOut.flush();                
			fileOut.close();
			
			return storeFile(dateFormat.format(date) +".txt");
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			return null;
		}
		
	}
}
